package com.jf.test.mvvm.base

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fawvw.vehice.netlib.base.BaseNetWorker
import com.fawvw.vehice.netlib.entity.HttpEvent
import com.fawvw.vehice.netlib.entity.RespEntity
import com.fawvw.vehice.netlib.retrofit.ReqCallback
import kotlinx.coroutines.*

/**
 * @Class: BasePresenter
 * @Description:
 * @author: github.com/jackyflame
 * @Date: 2021/3/10
 */
open class BasePresenter : BaseNetWorker {

    var vm: ViewModel

    constructor(mLifecycleOwner: LifecycleOwner, vm: ViewModel) : super(mLifecycleOwner) {
        this.vm = vm
    }

    private val error by lazy { MutableLiveData<Exception>() }

    private val finally by lazy { MutableLiveData<Int>() }

    fun <T> request(call:suspend () -> RespEntity<T>, callback: ReqCallback<T>?){
        vm.viewModelScope.launch {
            callback?.onReqStart()
            withContext(Dispatchers.IO){
                //call.invoke()
                call()
            }.apply {
                if(isSucceed){
                    callback?.onNetResp(data);
                }else{
                    callback?.onReqError(HttpEvent(code,errorMessage))
                }
            }
        }
    }

    fun <T> request(call:suspend () -> RespEntity<T>){
        vm.viewModelScope.launch {
            withContext(Dispatchers.IO){
                call.invoke()
            }
        }
    }

    fun launchUI(block: suspend CoroutineScope.()-> Unit) = vm.viewModelScope.launch {
        try {
            withTimeout(5000){
                block()
            }
        }catch (e:Exception){
            error.value = e
        }finally {
            finally.value = 200
        }
    }

}
